/*
 moxl - Modular XML Library
 Copyright (c) 2007, Malcolm Sparks

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package moxl.xpath;

import java.util.ArrayList;
import java.util.List;

import moxl.dom.MoxlNode;
import moxl.xpath.axes.InvalidAxisForNodeException;
import moxl.xpath.functions.LastFunction;
import moxl.xpath.functions.PositionFunction;
import moxl.xpath.parser.types.PathExpression;
import moxl.xpath.parser.types.Step;
import moxl.xpath.parser.types.XPathEvaluationException;

public class XPathParsedQuery<T extends MoxlNode>
{
	private final PathExpression pathExpression;

	XPathParsedQuery(PathExpression pathExpression)
	{
		this.pathExpression = pathExpression;
	}

	public List<Step> listSteps()
	{
		return pathExpression.listSteps();
	}

	@SuppressWarnings("unchecked")
	public final List<T> execute(MoxlNode contextNode) throws InvalidAxisForNodeException, XPathEvaluationException
	{
		FunctionMap functionMap = new FunctionMap();
		functionMap.add(new PositionFunction());
		functionMap.add(new LastFunction());
		XPathContext context = new XPathContext(contextNode, functionMap);
		List<MoxlNode> nodeSet = new ArrayList<MoxlNode>();
		nodeSet.add(contextNode);
		for (Step step : listSteps())
		{
			nodeSet = step.run(nodeSet, context);
		}
		return (List<T>) nodeSet;
	}

}
